package cn.edu.ctbu.datajpa01.service;

import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;

    public Page<Student> getAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }
    public List<Student> findAll(){
        return studentRepository.findAll();
    }

    public Boolean validUserNameAndPassword(String username, String password) throws Exception{

        List<Student> students=studentRepository.findByNameAndPassword(username,password);
        if(students.size()>0){
            return true;

        }else {
            throw new Exception("出错了，无效的用户名和密码！！");
        }

    }


    /**
     * 按id进行查询
     * @param id 主键，整数
     * @return
     */
    public Student findById(Integer id){
        return studentRepository.findById(id).orElse(null);
    }

    /**
     * 按name进行查询
     * @return
     */
    public List<Student> findByName(String name){
        return studentRepository.findByNameLike(name);
    }

    /**
     * 按名字进行查询
     * @param name
     * @param password
     * @return
     */

    public List<Student> findByNameAndPassword(String name, String password){
        return studentRepository.findByNameAndPassword(name, password);
    }

    public Student insert(Student student){
        return studentRepository.save(student);

    }

    public Student update(Student student){
        return studentRepository.save(student);
    }
    /*
    public void delete(Student student){
        studentRepository.delete(student);
    }
    */
    public void delete(Integer id){
        Student student=new Student();
        student.setId(id);
        studentRepository.delete(student);
    }

    public List<Student> findLastStudent() {
        return studentRepository.findStudentsWithMaxIdPrefix();
    }



}
